import {
    Dispatch
} from 'redux';

import ajax from './../../http';

import * as types from './../types/user';

interface LoginPara {
    username: string,
    password: string
}

interface SetUserProfilePayload {
    email?: string,
    nickName?: string,
    birthday?: string,
    gender?: number,
    matchGender?: number,
    matchAgeMin?: number,
    matchAgeMax?: number,
    about?: string,
    height?: number,
    body?: number,
    education?: number,
    relation?: number,
    haveChildren?: number,
    drinker?: number,
    countryId?: number,
    stateId?: number,
    cityId?: number,
    smoker?: number,
    orientation?: number,
    matchConnectionType?: number
}

interface UpdateUserMatchPayload {
    countryId?: number,
    stateId?: number,
    cityId?: number,
    minAge?: number,
    maxAge?: number,
    seeking?: number,
    isOnline?: 0 | 1,
    orientation?: number,
    connectionType?: number
}

interface DeleteAccountPayload {
    leavingReason: string,
    password: string
}

interface RegisterPara {
    username:string,
    email:string,
    passwd:string
}

interface BindUserPhotoPara {
    attachIds: Array<string>,
    avatarAId: string
}

interface VerifyPhotoPara {
    attachIds: Array<string>
}

export default {
    //用户登录
    [types.userLogin](
        payload: LoginPara
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    userId
                } = await ajax.post(
                    `user/login`, payload
                ) as any;

                const userInfo = {
                    userId:userId
                }

                dispatch({
                    data: userInfo,
                    type: types.userLogin
                })
            }
            catch (e) {
                return Promise.reject(e)
            }
        }
    },
    //验证图片
    [types.userVerifyPhoto](
        payload: VerifyPhotoPara
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    message
                } = await ajax.post(
                    `user/verification/photo`, payload
                )
                dispatch({
                    type: types.userLogin,
                    data: { photoVerify: 3 }
                })
                return message;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //用户注册
    [types.register](
        payload: RegisterPara
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    userId
                } = await ajax.post(
                    `user/account`, payload
                ) as any;

                const userInfo = {
                    userId:userId
                }

                dispatch({
                    data: userInfo,
                    type: types.userLogin
                })
            }
            catch (e) {
                return Promise.reject(e)
            }
        }
    },
    //用户绑定图片
    [types.bindUserPhoto](
        payload: BindUserPhotoPara
    ) {
        return async () => {
            try {
                await ajax.put(
                    `user/photos`, payload
                )
                await this[types.loginUser]()
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //删除用户图片
    [types.deleteUserPhoto](
        photoId: string
    ) {
        return async (dispatch: Dispatch) => {
            const _url = `user/photo/${photoId}`;
            try {
                await ajax.delete(_url);
                dispatch({
                    data: photoId,
                    type: types.deleteUserPhoto
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //用户退出登录
    [types.userLoginOut]() {
        return async (dispatch: Dispatch) => {
            try {
                await ajax.delete(
                    `user/session`
                )
                dispatch({
                    type: types.userLoginOut
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //检查用户当前的登录状态
    [types.loginStatus]() {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    userId = 0
                } = await ajax.get(
                    `user/login/status`
                )
                const isLogin = !!userId;

                const _type = isLogin ?
                    types.userLogin :
                    types.userLoginOut;

                const _data = {
                    userId: userId
                }

                dispatch({
                    type: _type,
                    data: _data
                })

                return userId;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取当前登录用户
    [types.loginUser](_userId?: string) {
        return async (
            dispatch: Dispatch,
            getState:Function
        ) => {
            const _store = getState() as any;
            const {
                user = {}
            } = _store;

            const {
                loginUser = {}
            } = user;

            const {
                userId
            } = loginUser;

            try {
                const userInfo = await this[
                    types.getUserProfile
                ](_userId || userId);

                dispatch({
                    data: userInfo,
                    type: types.userLogin
                })

                return userInfo;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取某个用户的信息详情
    [types.getUserProfile](userId?: string) {
        return async (dispatch: Dispatch) => {
            try {
                const userInfo = await (
                    ajax.get(`user/${userId}/profile`)
                )
                dispatch({
                    data: userInfo,
                    type: types.getUserProfile
                })
                return userInfo;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //设置当前用户的基本信息
    [types.setUserProfile](payload: SetUserProfilePayload) {
        return async (dispatch: Dispatch) => {
            try {
                const _para = {
                    basicInfo: payload
                }
                const userInfo = (
                    await ajax.put(`profile/basic`, _para)
                )
                dispatch({
                    data: userInfo,
                    type: types.userLogin,
                })
                return userInfo;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取当前用户的match信息
    [types.getUserMatch]() {
        return async (
            dispatch: Dispatch,
            getState:Function
        ) => {
            const _store = getState() as any;
            const {
                user = {}
            } = _store;

            const {
                loginUser = {}
            } = user;

            const {
                userId
            } = loginUser;
            try {
                const _url = (
                    `user/${userId}/profile/match`
                )
                const match = (
                    await ajax.get(_url)
                )
                const _data = {
                    ...match,
                    userId: userId
                }
                dispatch({
                    data: _data,
                    type: types.getUserMatch
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //更新当前用户的match信息
    [types.updateUserMatch](
        payload: UpdateUserMatchPayload
    ) {
        return async (dispatch: Dispatch, getState:Function) => {
            const _store = getState() as any;
            const {
                user = {}
            } = _store;

            const {
                loginUser = {}
            } = user;

            const {
                userId
            } = loginUser;

            try {
                const _para = {
                    matchInfo: payload
                };

                const match = await (
                    ajax.put(`profile/match`, _para)
                );

                await this[types.loginUser](userId);

                const _data = {
                    ...match,
                    userId: userId
                }

                dispatch({
                    data: _data,
                    type: types.getUserMatch
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //删除当前用户
    [types.userDelete](payload: DeleteAccountPayload) {
        return async (dispatch: Dispatch) => {
            try {
                await ajax.delete(
                    `user/deleteAccount`, payload
                )
                await this[types.userLoginOut]();
                dispatch({
                    type: types.userDelete
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //修改密码
    [types.resetPassword](email:string) {
        return async (dispatch: Dispatch) => {
            const _url = `user/password/changing`;
            try {
                await ajax.post(_url, {
                    email:email
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //修改用户的邮箱
    [types.changeUserEmail](
        email:string,password:string
    ) {
        return async (dispatch: Dispatch) => {
            const para = {
                email,
                password
            }
            try {
                await ajax.put(
                    `user/email`,para
                )
                dispatch({
                    data:{ email },
                    type:types.userLogin
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取所有用户数据数
    [types.getUserItemsTotal]() {
        return async (dispatch: Dispatch) => {
            const res = await ajax.get(
                `connection/status`
            )
            dispatch({
                data:res,
                type:types.getUserItemsTotal
            })
        }
    }
}